﻿// <copyright file="ComUtility.cs" company="City of Portland, BES-ASM">
// </copyright>
// <summary>ComUtilty class.</summary>

namespace BESASM.EMGAATS.Arc
{
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Runtime.InteropServices;
  using System.Text;

  /// <summary>
  /// A class for managing COM objects
  /// </summary>
  public static class ComUtility
  {
    /// <summary>
    /// Adds a COM reference to the given COM object
    /// </summary>
    /// <param name="comObject">The COM object to add a reference to</param>
    /// <remarks>Only add a reference if you need to "own" the object separately from other objects (so that if other objects
    /// try to release this object there is still a reference to it).</remarks>
    public static void AddReference(object comObject)
    {
      if (comObject != null && Marshal.IsComObject(comObject))
      {
        IntPtr ptr = Marshal.GetIUnknownForObject(comObject);
        Marshal.GetObjectForIUnknown(ptr);
      }
    }

    /// <summary>
    /// Releases a single reference from a COM object
    /// </summary>
    /// <param name="comObject">The COM object to release</param>
    /// <returns>The number of remaining references on the object, or 0 if the object is not a COM object</returns>
    public static int ReleaseComObject(object comObject)
    {
      if (comObject != null && Marshal.IsComObject(comObject))
      {
        return Marshal.ReleaseComObject(comObject);
      }
      else
      {
        return 0;
      }
    }
  }
}
